package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.app.util.UserContext;
import cn.wolfcode.trip.base.domain.*;
import cn.wolfcode.trip.base.domain.UserComment;
import cn.wolfcode.trip.base.query.TravelQueryObject;
import cn.wolfcode.trip.base.service.ITravelService;
import cn.wolfcode.trip.base.service.*;
import cn.wolfcode.trip.base.service.IUserCommentService;
import cn.wolfcode.trip.base.service.IUserService;
import cn.wolfcode.trip.base.util.JSONResult;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


//该项目是符合REST规范的,此时该控制器表示操作用户的资源
@RestController //Controller+ResponseBody
@RequestMapping("/users")
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private ITravelService travelService;
    @Autowired
    private IUserCommentService userCommentService;
    @Autowired
    private IMessageService messageService;
    @Autowired
    private IStrategyService strategyService;


    /*
    更新某个用户的游记
    资源:/users/{authorId}/travels
    动作:PUT
    参数:很多...(参考数据库表)
     */
    @PutMapping("/{authorId}/travels")
    public Object updateTravels(Travel entity) {
        travelService.saveOrUpdate(entity);
        return new JSONResult();
    }

    /*
    保存某个用户的游记
    资源:/users/{authorId}/travels
    动作:POST
    参数:很多...(参考数据库表)
     */
    @PostMapping("/{authorId}/travels")
    public Object saveTravels(Travel entity) {
        //自动填充作者
        entity.setAuthor(UserContext.getCurrentUser());
        travelService.saveOrUpdate(entity);
        return new JSONResult();
    }

    /*
    获取某个用户的所有游记(带有分页功能)
    资源:/users/{authorId}/travels
    动作:GET
    参数:currentPage=x
     */
    @GetMapping("/{authorId}/travels")
    public Object queryTravel(TravelQueryObject qo) {
        //需要按照发布时间排序,这里设置下
        qo.setOrderBy("t.lastUpdateTime desc");
        qo.setState(null);
        PageInfo<Travel> info = travelService.queryTravel(qo);
        return info;
    }

    /*
        注册用户的接口
        资源:/users
        动作:POST
        参数:email=xx&nickName=xx&password=xx
     */
    @PostMapping
    public Object regist(User u) {
        JSONResult result = new JSONResult();
        try {
            //调用业务层注册的方法
            userService.regist(u);
            result.setData(u); //设置当前登录的用户,一起返回
        } catch (Exception e) {
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }

    /*
    更新用户信息
    资源:/users/{id}
    动作:PUT
    参数:nickName=xx&gender=xx&place=xx&sign=xx&headImgUrl=xx&coverImgUrl=xx
     */
    @PutMapping("/{id}")
    public Object updateUser(User u) {
        JSONResult result = new JSONResult();
        try {
            //调用业务层注册的方法
            userService.saveOrUpdate(u);
            result.setData(u); //设置当前登录的用户,一起返回
        } catch (Exception e) {
            e.printStackTrace();
            result.mark(e.getMessage());
        }
        return result;
    }

    /*
     获得用户的点赞以及评论等信息
     */
    @GetMapping("/messages")
    public Object getMessage() {
        User user = UserContext.getCurrentUser ();
        Message message = messageService.getMessage (user.getId ());
        messageService.setMessagetoNull (user.getId ());
        return message;
    }
    /*=========================================================================*/

    /*
    根据用户id获取所有信息
    资源:/users/getUserById
    动作:GET
    参数:
     */
    @GetMapping("/{id}/userId")
    public Object getUserById(@PathVariable Long id) {
        return userService.getByUserId(id);
    }

    /*
     获得用户还未读过的关于游记评论
    根据当前登录人id,和目标id去查询是否有关注
    资源:/users/getCurrentIdByTargetId
    动作:GET
    参数:
     */
    @GetMapping("/messages/comment/travel")
    public Object getTravelComment() {
        User user = UserContext.getCurrentUser ();
        messageService.setCommnetToRead (user.getId ());
        List<UserComment> travelDiscusses = messageService.getCommentOfTravel (user.getId ());
        return travelDiscusses;

    }

    /*获得用户还未读过的关于攻略的评论*/
    @GetMapping("/messages/comment/strategy")
    public Object getStrategyComment() {
        User user = UserContext.getCurrentUser ();
        List<UserComment> travelDiscusses = messageService.getCommentOfStrategyComment (user.getId ());
        return travelDiscusses;
    }

    @GetMapping("/focus")
    public Object getCurrentIdByTargetId(Long currentId, Long targetId) {
        Map<String, Object> map = new HashMap<> ();
        map.put ("num", userService.getCurrentIdByTargetId (currentId, targetId));
        return map;
    }

    @RequestMapping("/insert")
    public Object insert(Long currentId, Long targetId) {
        userService.save(currentId, targetId);
        int fansNum = userService.updateFansNum(targetId);
        return fansNum;
    }


    /**
     *  删除粉丝接口，zbj修改于2018.11.17 15:41
     * @return 返回更新后的粉丝数
     */
    /*
    获得用户还未读过的点赞
     */
    @GetMapping("/messages/like")
    public Object getTravelLike() {
        User user = UserContext.getCurrentUser ();
        List<TravelLike> likes = messageService.getTravelLikeOfNOReader (user.getId ());
        return likes;
    }


    /**
     *  删除粉丝接口，zbj修改于2018.11.17 15:41
     * @param currentId
     * @param targetId
     * @return 返回更新后的粉丝数
     */
    @RequestMapping("/delete")
    public Object delete(Long currentId, Long targetId) {
        userService.delete(currentId, targetId);
        int fansNum =  userService.removeFansNum(targetId);
        return fansNum;
    }


    /**
     * 获取个人用户积分
     *
     */
    @GetMapping("/{id}/score")
    public Object getUserScore(@PathVariable Long id){

        return userService.getUserScore(id);
    }


    /**
     * 保存一条评论的回复
     *
     * @param
     * @return
     */
    /*
     * /messages/atmes/strategys*/
    @GetMapping("/messages/atmes/strategys")
    public Object getAtmeStrategys() {
        User user = UserContext.getCurrentUser ();
        List<AtMe> atMes = messageService.getAtMeOfNoReader (user.getId (), AtMe.THEME_STRATEGY);
        return atMes;
    }

    @GetMapping("/messages/atmes/travels")
    public Object getAtmeTravels() {
        User user = UserContext.getCurrentUser ();
        messageService.setAtToRead (user.getId ());
        List<AtMe> atMes = messageService.getAtMeOfNoReader (user.getId (), AtMe.STATE_TRAVEL);
        return atMes;
    }

    @PostMapping("/usercomments/{user.id}")
    public Object saveCommentReply(UserComment userComment) {
        JSONResult result = new JSONResult ();
        try {
            userCommentService.saveCommentReply (userComment);

            String msg = userComment.getComment ();
            String[] a = msg.split ("@");
            if(a.length>1){
                String[] b = a[1].split (",");
                String des = b[0];
                messageService.insertAtme (des, userComment);
            }
        } catch (Exception e) {
            e.printStackTrace ();

            result.mark (e.getMessage ());
        }
        return result;
    }

    /*
    获得用户未读过的私信
     */
    @GetMapping("/messages/letter")
    public Object getletter() {

        User user = UserContext.getCurrentUser ();
        messageService.setLetterToRead (user.getId ());
        List<PrivateLetter> letters = messageService.getLetterOfNoreader (user.getId ());
        return letters;

    }

    /*
   获得用户未读过的系统消息
    */
    @GetMapping("/messages/systemmessage")
    public Object getSystemMessage() {

        User user = UserContext.getCurrentUser ();
        messageService.setSystemMessageToReader (user.getId());
        List<SystemMessage> messages = messageService.getSystemMessageOfNoreader (user.getId());
        return messages;

    }

    /**
     * 获得用户获得的点赞
     */
    @GetMapping("/messages/userlike")
    public  Object getUserLike(){
        User user = UserContext.getCurrentUser ();
        messageService.setUserLikeToread(user.getId());
        List<UserLike> userLikes = messageService.getUserLike(user.getId());
        return userLikes;
    }



    /**
     * 保存一条攻略下的用户评论/回复
     *
     * @param userComment
     * @return
     */
    @PostMapping("/{becommented.id}/usercomments/{user.id}")
    public Object addComment(UserComment userComment) {
        JSONResult result = new JSONResult ();
        try {
            userCommentService.saveStrategyComment (userComment);
            String msg = userComment.getComment ();
            String[] a = msg.split ("@");
            if(a.length>1){
                String[] b = a[1].split (",");
                String des = b[0];
                messageService.insertAtme (des, userComment);
            }

        } catch (Exception e) {
            e.printStackTrace ();
            result.mark (e.getMessage ());
        }
        return result;
    }

    /**
     * 保存一条评论的回复
     * @param privateLetter
     * @return
     */
    @PostMapping("/letter")
    public Object reviewLetter(PrivateLetter privateLetter) {
        JSONResult result = new JSONResult();
        try {
            User user = UserContext.getCurrentUser();
            privateLetter.setPostUser(user);
            messageService.insertLetter(privateLetter);

        } catch (Exception e) {
            result.mark(e.getMessage());
        }
        return result;
    }

    /**
     * 根据用户id查询他收藏的游记
     * @param id
     * @return
     */
    @GetMapping("/{id}/collects/travels")
    public List<Travel> getCollectTravels(@PathVariable Long id) {
        List<Travel> travelList = travelService.listCollectTravelsByUserId(id);
        return travelList;
    }



    /**
     * 根据用户id查询他收藏的攻略
     * @param id
     * @return
     */
    @GetMapping("/{id}/collects/strategies")
    public List<Strategy> getCollectStrategies(@PathVariable Long id) {
        List<Strategy> strategyList = strategyService.getCollectStrategies(id);
        return strategyList;
    }



}